package com.newthread.android.camera;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.telephony.SmsMessage;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.newthread.android.activity.main.MyApplication;
import com.newthread.android.manager.LocationManager;
import com.newthread.android.manager.MailManager;
import com.newthread.android.util.AndroidUtil;
import com.newthread.android.util.Loger;
import com.newthread.android.util.MyPreferenceManager;

/**
 * 防盗服务类
 * Funcation : 发送带照片和地理信息和来短信后的邮件到指定邮箱
 */
public class FangDaoService extends Service {
    //防盗服务状态，默认关闭。
    private ServiceState state = EndSrerviceState.getInstance();
    //刚开始 没有注册广播
    private Boolean isRegistReceiver = false;

    @Override
    public void onDestroy() {
        Intent localIntent = new Intent();
        localIntent.setClass(this, FangDaoService.class);
        this.startService(localIntent);
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;
        checkSim();
        if (!isRegistReceiver) {
            registeFangDaoReceiver();
        }
        Loger.V("防盗状态" + state.getIsaLive());
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 动态的以最高权限注册该广播
     */
    class FangDaoReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            MyPreferenceManager.init(context);
            // 来短信后
            if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
                dealSms(intent);
            }
            // 点亮屏幕时拍照.
            if (intent.getAction().equals("android.intent.action.SCREEN_ON")) {
                if (state.getIsaLive()) {
                    // 定位回调函数
                    LocationManager.getInstance(getApplicationContext()).setBdLocationListener(new BDLocationListener() {
                        @Override
                        public void onReceiveLocation(final BDLocation bdLocation) {
                            LocationManager.getInstance(getApplicationContext()).stop();
                            //定位成功后，拍照发图
                            takePicture(bdLocation);
                        }
                    });
                    //开始定位
                    LocationManager.getInstance(getApplicationContext()).start();
                }
            }

        }

        /**
         * 处理短信
         *
         * @param intent
         */
        private void dealSms(Intent intent) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                StringBuilder SMSAddress = new StringBuilder();
                StringBuilder SMSContent = new StringBuilder();
                filterSms(SMSAddress, SMSContent, bundle);
                dealSpecialSms(SMSContent.toString());
                if (state.getIsaLive()) {
                    String mail = MyPreferenceManager.getString("mail", "jdp112233@qq.com");
                    String pwd = MyPreferenceManager.getString("mailPwd", "1314520");
                    //如果没有配置邮箱 就发送到我的邮箱
                    MailManager.getInstance().sendEmail(mail, pwd, mail, "人在民大防盗邮件", "from:" + getPeople(SMSAddress.toString()) + " content:" + SMSContent.toString(), null, null);
                }
            }
        }

        /**
         * 将短信bundle分解成 SMSAddress,SMSContent
         *
         * @param SMSAddress - 发送人的号码
         * @param SMSContent - 收到的内容
         * @param bundle     - 短信bundle
         */
        private void filterSms(StringBuilder SMSAddress, StringBuilder SMSContent, Bundle bundle) {
            Object[] pdusObjects = (Object[]) bundle.get("pdus");
            SmsMessage[] messages = new SmsMessage[pdusObjects.length];
            for (int i = 0; i < pdusObjects.length; i++) {
                messages[i] = SmsMessage
                        .createFromPdu((byte[]) pdusObjects[i]);
            }
            for (SmsMessage message : messages) {
                SMSAddress.append(message
                        .getDisplayOriginatingAddress());
                SMSContent.append(message.getDisplayMessageBody());
            }
        }

        /**
         * 处理特殊短信
         *
         * @param SMSContent -短信内容
         */
        private void dealSpecialSms(String SMSContent) {
            if (SMSContent.contains("kaiqi")) {
                state = StartSrerviceState.getInstance();
                Loger.V("截获短信,开启防盗状态");
                abortBroadcast();
            }
            if (SMSContent.contains("guanbi")) {
                state = EndSrerviceState.getInstance();
               Loger.V("截获短信,关闭防盗状态");
                abortBroadcast();
            }
        }
    }

    /**
     * 照相并且发送邮件附带位置信息
     *
     * @param bdLocation － 位置信息
     */
    private void takePicture(final BDLocation bdLocation) {
        //拍照后回调函数,以MyApplication放如activity里面
        Object obj = new CameraActivity.CallBack() {
            @Override
            public void callResult(String result) {
                if (!result.contains("fail")) {
                    String addrStr = bdLocation.getAddrStr();
                    if (addrStr.length() <= 1)
                        addrStr = "";
                    String mail = MyPreferenceManager.getString("mail", "jdp112233@qq.com");
                    String pwd = MyPreferenceManager.getString("mailPwd", "1314520");
                    MailManager.getInstance().sendEmail(mail, pwd, mail, "人在民大防盗邮件,手机地址:" + addrStr + "纬度:" + bdLocation.getLatitude() + "经度:" + bdLocation.getLongitude(), addrStr, result, null);
                }
            }
        };
        MyApplication.getInstance().putThing("CameraActivity_callBack", obj);
        Intent _intent = new Intent(getApplicationContext(), CameraActivity.class);
        _intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        _intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(_intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        state = StartSrerviceState.getInstance();
    }

    private void registeFangDaoReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        filter.addAction("android.intent.action.SCREEN_ON");
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(new FangDaoReceiver(), filter);
        isRegistReceiver = true;
    }

    /**
     * 当测试发送成功后,将simSerialNumber写入Preference
     * 检查sim卡是否更改，更改后开启防盗功能.
     */
    public void checkSim() {
        String currentSim = AndroidUtil.getSimSerialNumber(getApplicationContext());
        MyPreferenceManager.init(getApplicationContext());
        String mySim = MyPreferenceManager.getString("telNumber", "8888888");
        if (currentSim != null && !currentSim.equals(mySim)) {
            state = StartSrerviceState.getInstance();
        }
    }

    /**
     * 从号码解析出联系人信息
     *
     * @param number －号码
     * @return - 联系人姓名+号码
     */
    private String getPeople(String number) {
        String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER};
        number = number.substring(number.length() - 11, number.length());

        Cursor cursor = this.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                projection, // Which columns to return.
                ContactsContract.CommonDataKinds.Phone.NUMBER + " = '" + number
                        + "'", // WHERE clause.
                null, // WHERE clause value substitution
                null); // Sort order.

        if (cursor == null) {
            return number;
        }
        String allName = "";
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);
            int nameFieldColumnIndex = cursor
                    .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            String name = cursor.getString(nameFieldColumnIndex);
            allName = allName + name;
        }
        return allName + number;
    }

}
